package de.uhlesoluschns.opensearch.ui;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.apache.commons.codec.DecoderException;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import de.uhlesoluschns.opensearch.OpenSearch;
import de.uhlesoluschns.opensearch.R;
import de.uhlesoluschns.opensearch.provider.XmlImporter;

public class SearchProvider extends Activity {
	
	private ContentValues engine;
	private Bitmap image;
	private XmlImporter importer;
	
	public SearchProvider() {
		importer = new XmlImporter();
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_engine);
		
		Uri data = getIntent().getData();
		engine = null;
		
		try {
			engine = importer.parse(data);
			image = importer.loadImage(engine.getAsString("image"));
			if(image != null) {
				ByteArrayOutputStream imageStream = new ByteArrayOutputStream();
				image.compress(CompressFormat.PNG, 100, imageStream);
				engine.put("image", imageStream.toByteArray());
			} else {
				engine.remove("image");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (DecoderException e) {
			e.printStackTrace();
		}
		
		if(engine != null) {
			((TextView) findViewById(R.id.engineShortName)).setText(engine.getAsString("shortName"));
			((TextView) findViewById(R.id.engineDescription)).setText(engine.getAsString("description"));
			((ImageView) findViewById(R.id.engineImage)).setImageBitmap(image);
			((Button) findViewById(R.id.addEngine)).setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					ContentResolver resolver = getContentResolver();
					/*Uri engineUri = */ resolver.insert(OpenSearch.Provider.CONTENT_URI, engine);
					//TODO display notification to user
					finish();
				}
			});
		}
	}
}
